<template>
  <div class="question-container">
    <el-card class="question-card">
      <!-- 顶部信息栏 -->
      <div class="header">
        <div class="user-info">
          <el-tag type="info">考生: {{ userInfo.studentName }}</el-tag>
        </div>
        <div class="progress">
          <span>第 {{ currentIndex + 1 }} 题 / 共 {{ questions.length }} 题</span>
        </div>
      </div>

      <!-- 题目内容区域 -->
      <div class="question-content">
        <h3 class="question-text">{{ currentQuestion.questionText }}</h3>

        <el-radio-group
          v-model="answers[currentIndex]"
          class="options-group"
          @change="handleOptionChange"
        >
          <el-radio
            :label="'A'"
            class="option-item"
          >
            <span class="option-letter">A.</span> {{ currentQuestion.optionA }}
          </el-radio>
          <el-radio
            :label="'B'"
            class="option-item"
          >
            <span class="option-letter">B.</span> {{ currentQuestion.optionB }}
          </el-radio>
        </el-radio-group>
      </div>

      <!-- 导航按钮 -->
      <div class="navigation">
        <el-button
          :disabled="currentIndex === 0"
          @click="prevQuestion"
          class="nav-button"
        >
          上一题
        </el-button>

        <el-button
          v-if="currentIndex < questions.length - 1"
          type="primary"
          :disabled="!answers[currentIndex]"
          @click="nextQuestion"
          class="nav-button"
        >
          下一题
        </el-button>

        <el-button
          v-else
          type="success"
          :disabled="!answers[currentIndex] || !isAllAnswered"
          @click="submitTest"
          class="submit-button"
          :loading="submitting"
        >
          {{ submitting ? '提交中...' : '提交测试' }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request' // 导入您配置的axios实例

// 用户信息
const userInfo = ref(JSON.parse(localStorage.getItem('xm-pro-user')) || {})

// 题目数据
const questions = ref([])
const answers = ref([])
const currentIndex = ref(0)
const submitting = ref(false)

// 检查是否所有题目都已回答
const isAllAnswered = computed(() => {
  return answers.value.every(answer => answer !== null)
})

// 获取题目数据
const fetchQuestions = async () => {
  try {
    const res = await request.get('/mbti/question/list')
    if (res && res.data) {
      questions.value = res.data
      answers.value = new Array(res.data.length).fill(null)
    } else {
      ElMessage.error('获取题目数据格式不正确')
    }
  } catch (error) {
    ElMessage.error('获取题目失败')
    console.error('获取题目失败:', error)
  }
}

// 当前题目
const currentQuestion = computed(() => {
  return questions.value[currentIndex.value] || {}
})

// 选项变化处理
const handleOptionChange = (value) => {
  answers.value[currentIndex.value] = value
}

// 上一题
const prevQuestion = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--
  }
}

// 下一题
const nextQuestion = () => {
  if (currentIndex.value < questions.value.length - 1) {
    currentIndex.value++
  }
}

// 提交测试
const submitTest = async () => {
  if (!isAllAnswered.value) {
    ElMessage.warning('请完成所有题目后再提交')
    return
  }

  try {
    submitting.value = true
    console.log(userInfo)
    const payload = {
      userId: userInfo.value.studentId,
      answers: answers.value.map((answer, index) => ({
        questionId: questions.value[index].questionId,
        choice: answer
      }))
    }

    const res = await request.post('/mbti/question/submit', payload)

    if (res && res.code === "200") {
      ElMessage.success(res.message || '提交成功')
      // 这里可以跳转到结果页
      localStorage.setItem('xm-pro',JSON.stringify(res.data))
      setTimeout( () => {
        location.href = '/result'
      },500)
      // router.push({name:'result',query:JSON.stringify(res.data)})
    } else {
      ElMessage.error(res.message || '提交失败')
    }
  }finally {
    submitting.value = false
  }
}

// 初始化获取题目
onMounted(() => {
  fetchQuestions()
})
</script>

<style scoped>
/* 保持原有的样式不变 */
.question-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.question-card {
  width: 100%;
  max-width: 800px;
  border-radius: 12px;
  padding: 24px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.user-info {
  font-size: 16px;
}

.progress {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.progress span {
  color: #606266;
  font-size: 14px;
}

.question-content {
  margin: 40px 0;
}

.question-text {
  color: #303133;
  font-size: 20px;
  line-height: 1.6;
  margin-bottom: 30px;
}

.options-group {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.option-item {
  align-items: flex-start;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
  margin: 0 !important;
}

.option-item:hover {
  border-color: #409EFF;
  background-color: #f5f7fa;
}

.option-item.is-checked {
  border-color: #409EFF;
  background-color: #ecf5ff;
}

.option-letter {
  font-weight: bold;
  color: #409EFF;
  margin-right: 10px;
}

.navigation {
  display: flex;
  justify-content: space-between;
  margin-top: 40px;
}

.nav-button, .submit-button {
  min-width: 120px;
  height: 40px;
}

@media (max-width: 768px) {
  .question-card {
    padding: 16px;
  }

  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .progress {
    width: 100%;
    align-items: flex-start;
  }

  .question-text {
    font-size: 18px;
  }

  .option-item {
    padding: 12px;
  }

  .navigation {
    margin-top: 30px;
  }
}
</style>
